<template>
  <div class="comment-system">
    <!-- 评论列表 -->
    <div class="comments-list">
      <div v-for="(comment, index) in comments" :key="comment.id" class="comment-item">
        <div class="comment-content">{{ comment.content }}</div>
        <div class="comment-meta">
          <span class="author">{{ comment.author }}</span>
          <span class="time">{{ formatTime(comment.timestamp) }}</span>
        </div>
      </div>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input">
      <textarea
          ref="textareaRef"
          v-model="newComment"
          placeholder="输入评论（支持快捷键操作）"
          @keydown="handleKeyDown"
      ></textarea>
      <button @click="submitComment">提交</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  // 快捷键相关属性
  shortcuts: { type: [Object, Array], default: () => ({}) },
  preventDefault: { type: Boolean, default: false },
  stopPropagation: { type: Boolean, default: false },

  // 激活状态
  disabled: { type: Boolean, default: false },
  active: { type: Boolean, default: true },

  // 作用域
  target: { type: [String, Element], default: window },

  // 初始评论列表
  initialComments: { type: Array, default: () => [] }
})

const emit = defineEmits([
  'shortcut-triggered',
  'activated',
  'deactivated',
  'disabled-changed'
])

// 数据相关
const comments = ref([...props.initialComments])
const newComment = ref('')
const textareaRef = ref(null)

// 快捷键处理相关
const normalizedShortcuts = computed(() => {
  if (Array.isArray(props.shortcuts)) {
    return props.shortcuts
  }
  return Object.entries(props.shortcuts).map(([shortcut, action]) => ({
    shortcut,
    action
  }))
})

// 快捷键解析
const parseShortcut = (shortcut) => {
  const keys = shortcut.split('+').map(k => k.trim().toLowerCase())
  const modifiers = {
    ctrl: false,
    alt: false,
    shift: false,
    meta: false
  }
  let key = null

  for (const k of keys) {
    switch (k) {
      case 'ctrl': modifiers.ctrl = true; break
      case 'alt': modifiers.alt = true; break
      case 'shift': modifiers.shift = true; break
      case 'meta': modifiers.meta = true; break
      default: key = k
    }
  }

  if (!key) {
    console.warn(`Invalid shortcut: ${shortcut}`)
    return null
  }

  return { modifiers, key }
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (props.disabled || !props.active) return

  const pressedKey = event.key.toLowerCase()
  const pressedModifiers = {
    ctrl: event.ctrlKey,
    alt: event.altKey,
    shift: event.shiftKey,
    meta: event.metaKey
  }

  for (const { shortcut, action } of normalizedShortcuts.value) {
    const parsed = parseShortcut(shortcut)
    if (!parsed) continue

    const { modifiers, key } = parsed
    if (
        modifiers.ctrl === pressedModifiers.ctrl &&
        modifiers.alt === pressedModifiers.alt &&
        modifiers.shift === pressedModifiers.shift &&
        modifiers.meta === pressedModifiers.meta &&
        key === pressedKey
    ) {
      if (props.preventDefault) event.preventDefault()
      if (props.stopPropagation) event.stopPropagation()
      emit('shortcut-triggered', shortcut, action)
      handleAction(action)
    }
  }
}

// 动作处理
const handleAction = (action) => {
  switch (action) {
    case 'submit':
      submitComment()
      break
    case 'clear':
      newComment.value = ''
      break
      // 可以扩展更多动作
  }
}

// 提交评论
const submitComment = () => {
  if (newComment.value.trim()) {
    comments.value.push({
      id: Date.now(),
      content: newComment.value.trim(),
      author: '当前用户',
      timestamp: new Date()
    })
    newComment.value = ''
  }
}

// 时间格式化
const formatTime = (date) => {
  return new Date(date).toLocaleString()
}

// 快捷键监听管理
let targetElement = null
const setupListeners = () => {
  if (typeof props.target === 'string') {
    targetElement = document.querySelector(props.target)
  } else {
    targetElement = props.target
  }

  if (targetElement) {
    targetElement.addEventListener('keydown', handleKeyDown)
  }
}

const cleanupListeners = () => {
  if (targetElement) {
    targetElement.removeEventListener('keydown', handleKeyDown)
  }
}

// 生命周期
onMounted(() => {
  if (props.active) setupListeners()
})

onUnmounted(cleanupListeners)

// 状态监听
watch(() => props.active, (newVal) => {
  if (newVal) {
    setupListeners()
    emit('activated')
  } else {
    cleanupListeners()
    emit('deactivated')
  }
})

watch(() => props.disabled, (newVal) => {
  emit('disabled-changed', newVal)
})

watch(() => props.target, () => {
  cleanupListeners()
  setupListeners()
})
</script>

<style scoped>
.comment-system {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.comments-list {
  margin-bottom: 20px;
}

.comment-item {
  padding: 10px;
  margin: 10px 0;
  border-bottom: 1px solid #ddd;
}

.comment-content {
  margin-bottom: 5px;
}

.comment-meta {
  font-size: 0.8em;
  color: #666;
}

.comment-input textarea {
  width: 100%;
  height: 80px;
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #33a06f;
}
</style>